<?
require_once('functions.php');

function GetUsers()
{
        $conn = GetConnection();
		return $conn->query('SELECT * FROM Customers');
        //return $conn->query('SELECT U.*, K.Name FROM 2012UG_Users U Join 2012UG_Keywords K ON U.Keyword_id = K.id');
}
function BlankUser()
{
        return array('FirstName'=>null,'LastName'=>null,'Keyword_id'=>null,'created_at'=>null,'updated_at'=>null,'id'=>null);
}
function GetUser($id)
{
        $conn = GetConnection();
        $sql = "SELECT * FROM Customers WHERE U.id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}
function GetMethod($id, $table)
{
	    $conn = GetConnection();
        $sql = "SELECT * FROM $table WHERE Customers_id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $pay = $results;
        $conn->close();
        return $pay;
}
function SaveUser(&$row)
{
        $conn = GetConnection();
        $row2 = EscapeRow($row, $conn);
        if(empty($row['id']))
        {
                $sql =  "Insert 2012UG_Users (FirstName, LastName, Keyword_id, created_at) "
                        .       " Values ('$row2[FirstName]','$row2[LastName]', '$row2[Keyword_id]', NOW() ) ";
        }else{
                $sql =  "UPDATE 2012UG_Users "
                        .       "Set FirstName='$row2[FirstName]', LastName='$row2[LastName]', Keyword_id='$row2[Keyword_id]' "
                        .       "WHERE id=$row2[id] ";
        }
        $results = $conn->query($sql);
        //echo $sql;
        $error = $conn->error;
        if(empty($row['id']) && empty($error))
        {
                $row['id'] = $conn->insert_id;
        }
        $conn->close();
        
        return $error == '' ? true : array('SQL Error' => $error);
}
function DeleteUser($id)
{
        $conn = GetConnection();
        $sql =  "DELETE FROM 2012UG_Users WHERE id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $error = $conn->error;
        $conn->close();
        
        return $error == '' ? true : array('SQL Error' => $error);
}
function ValidateUser($row)
{
        $errors = array();
        if(empty($row['FirstName'])) $errors['FirstName'] = 'First Name is required';
        if(empty($row['LastName'])) $errors['LastName'] = 'Last Name is required';
        if(!is_numeric($row['Keyword_id'])) $errors['Keyword_id'] = 'Keyword_id must be a number';
        if(empty($row['Keyword_id'])) $errors['Keyword_id'] = 'Keyword_id is required';
        
        return count($errors) == 0 ? true : $errors;
}
